var tgd = tgd || {};
tgd.Contests = tgd.Contests || {};
tgd.Contests.SameGame = tgd.Contests.SameGame || {};
tgd.Contests.SameGame.Solver = tgd.Contests.SameGame.Solver || {};
tgd.Contests.SameGame.View = tgd.Contests.SameGame.View || {};


tgd.Contests.SameGame.Block = function (id, color, row, column) {
	var _id = id;
	var _color = color;
	var _row = row;
	var _col = column;
	var _group = null;
	var _neighbors;

	this.__defineGetter__("ID", function() { return _id; });
	this.__defineGetter__("Color", function() { return _color; });
	this.__defineGetter__("Row", function() { return _row; });
	this.__defineGetter__("Column", function() { return _col; });
	this.__defineGetter__("Group", function() { return _group; });
	this.__defineGetter__("isInGroup", function() { return _group !== null; });
	this.__defineGetter__("Code", function() { return String.fromCharCode(this.Row + 65) + this.Column; });
	this.__defineGetter__("HTMLColor", function() {
		var retVal;
		switch (_color) {
			case 1: retVal = "#f00"; break;
			case 2: retVal = "#0f0"; break;
			case 3: retVal = "#00f"; break;
			case 4: retVal = "#ff0"; break;
			case 5: retVal = "#f0f"; break;
			case 6: retVal = "#00f"; break;
			case 7: retVal = "#fff"; break;
			default: retVal = "#000";
		}
		return retVal;
	});

	this.__defineSetter__("Row", function(row) { _row = row; });
	this.__defineSetter__("Column", function(column) { _col = column; });



	/*
	 * Returns true if this is the first block in the group or does not have a group.
	 */
	this.calcGroups = function(group) {
		var isFirstBlockInGroup = false;

		if (_group !== null) {
			return isFirstBlockInGroup;  //false
		} else if (group === null || group === undefined) {
			_group = new tgd.Contests.SameGame.Group();
			_group.add(this);
			isFirstBlockInGroup = true;
		} else {
			_group = group;
			_group.add(this);
		}

		for (var i = 0; i < _neighbors.length; ++i) {
			if (_neighbors[i] !== null && _color === _neighbors[i].Color) {
				_neighbors[i].calcGroups(_group);
			}
		}

		if (_group.Size === 1) {
			_group = null;
		}

		return isFirstBlockInGroup;
	}



	this.setNeighbors = function(b1, b2, b3, b4) {
		_group = null;
		_neighbors = new Array();

		if (b1 !== undefined) {
			_neighbors.push(b1);
		}

		if (b2 !== undefined) {
			_neighbors.push(b2);
		}

		if (b3 !== undefined) {
			_neighbors.push(b3);
		}

		if (b4 !== undefined) {
			_neighbors.push(b4);
		}
	}

	this.move = function(row, column) {
		_row = row;
		_col = column;
		_group = null;

		this.setNeighbors();
	}

	this.toString = function() {
		return "ID: " + this.ID + "   Color: " + this.Color + "   Row: " + this.Row + "   Column: " + this.Column + "   Code: " + this.Code;
	}
}
